package com.ruoyi.common.utils.wx;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;

public class WxSend {
	
	public final static String secret = "425b6fb97a088f5e716f817691a038e7";
	public final static String appid = "wx1855378bf2b9bc83";
	public static String token;
	
	public boolean sendWx(String name,String code,String createUser,String riq,String status,String toUser,String url){
		try {
			//获取Token
			if(token==null){
				token = getToken(appid,secret);
			}
			
			String wxInvokeUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
			
			//消息模板
			String param = "{"
					+ "\"touser\":\""+toUser+"\","//发送给谁
					+ "\"template_id\":\"sm_gqa09_Fxgh77uH002j3sx4VGy_kSGmAJbemkuZlM\","
					+ "\"url\":\""+url+"\","
//					+ "\"client_msg_id\":\""+IdUtils.simpleUUID()+"\","
					+ "\"data\":{\"thing3\":{\"value\":\""+name+"\"},"//单据名称
					+ "\"thing4\":{\"value\":\""+code+"\"},"//单据编号
					+ "\"thing6\":{\"value\":\""+createUser+"\"},"//提交人员
					+ "\"time12\":{\"value\":\""+riq+"\"},"//日期
					+ "\"thing5\":{\"value\":\""+status+"\"}}"//单据状态
					+ "}";
			
			//调用
			HttpUtils.sendPost(wxInvokeUrl,new String(param.getBytes("UTF-8"), "UTF-8"));
		} catch (Exception e) {
			// TODO: handle exception
			e.getLocalizedMessage();
		}
		
		return true;
	}
	
//	public static void main(String[] args) {
//		
//		String token = getToken(appid,secret);
//		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
//		
//		String touser1="oeW8c6zR7lIkqThkhmSd5EipUvOQ";
//		String param = "{"
//				+ "\"touser\":\""+touser1+"\","//发送给谁
//				+ "\"template_id\":\"sm_gqa09_Fxgh77uH002j3sx4VGy_kSGmAJbemkuZlM\","
//				+ "\"url\":\"http://lkgnews.cn:90\","
////				+ "\"miniprogram\":{\"appid\":\""+appid+"\","
////				+ "\"path\":\"index?foo=bar\"},"
//				+ "\"client_msg_id\":\"MSG_111\","
//				+ "\"data\":{\"thing3\":{\"value\":\"测试消息通知\"},"//单据名称
//				+ "\"thing4\":{\"value\":\"2023-01\"},"//单据编号
//				+ "\"thing6\":{\"value\":\"韩先生\"},"//提交人员
//				+ "\"time12\":{\"value\":\"2023-08-08\"},"//日期
//				+ "\"thing5\":{\"value\":\"订单审核\"}}"//单据状态
//				+ "}";
//		HttpUtils.sendPost(url, param);
//	}
	
	private static String getToken(String appid,String secret){
		try {
			String tokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
			String tokenjson = HttpUtils.sendGet(tokenurl);
			JSONObject json = JSONObject.parseObject(tokenjson);
			token = json.get("access_token").toString();
			
		} catch (Exception e) {
			// TODO: handle exception
			String tokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
			String tokenjson = HttpUtils.sendGet(tokenurl);
			JSONObject json = JSONObject.parseObject(tokenjson);
			token = json.get("access_token").toString();
		}
		
		return token;
	}
}